/*
 * @(#)TestsetAction.java
 *
 *
 *
 * ver 1.0 Sep 6, 2007 ggranum
 */
package org.testfire.realm.view.json.action;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.testfire.realm.control.exception.UpdateException;
import org.testfire.realm.control.testfire.TestFireDBAO;
import org.testfire.realm.control.user.UserBean;
import org.testfire.realm.model.entities.testfire.AgentEntity;
import org.testfire.realm.view.json.translator.AgentTranslator;

// eof: TestsetAction.java

public class AgentAction<T> implements JsonAction<String>
{

    TestFireDBAO testfireDBAO;

    UserBean userBean;

    AgentTranslator agentTranslator;

    // Inject the lgsrealm entity manager, as defined in the persistence.xml file.
    @PersistenceContext(unitName = "testfire")
    EntityManager em;

      @Resource
    private UserTransaction utx;

    Logger log = Logger.getLogger(AgentAction.class);

    public String perform( String[] argumentKeys, String... args )
        throws UpdateException
    {
        try
        {

            utx.begin();
            if ( args[0].equals( "commit" ) )
            {
                AgentEntity translatedObj = agentTranslator.toObject( args[1] );
                // commit only occurs for objects that exist in the database:
                AgentEntity agent = em.merge( em.find( AgentEntity.class, translatedObj.getId() ));
                agentTranslator.copyValues( agent, translatedObj );
                em.merge( agent );
                em.flush();

            }
            else if ( args[0].equals( "clear_testset" ) )
            {
                // commit only occurs for objects that exist in the database:
                AgentEntity agent = em.merge( em.find( AgentEntity.class, Integer.parseInt(args[1]) ));
                agent.setHastestset( null );
                em.merge(agent);
            }
            utx.commit();
            return "success";
        }
        catch ( JSONException e )
        {
            log.error( "", e);
        }
        catch(Exception ex){
            log.error( "", ex);
        }
        return null;
    }

    public void setTestfireDBAO( TestFireDBAO testfireDBAO )
    {
        this.testfireDBAO = testfireDBAO;
    }

    public void setUserBean( UserBean userBean )
    {
        this.userBean = userBean;
    }

    public void setAgentTranslator( AgentTranslator agentTranslator )
    {
        this.agentTranslator = agentTranslator;
    }
}